<template>
  <el-dialog :close-on-click-modal='false' title="添加角色" :visible.sync="dialogFormVisible" :before-close="cancel">
    <el-form ref="form" :model="form" label-width="100px">
      <template>
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedRole" @change="handlecheckedRoleChange">
          <el-checkbox v-for="data, index in optionList" :disabled="data.status == 1" :label="data.roleId" :key="index">{{
            data.roleName
          }}</el-checkbox>
        </el-checkbox-group>
      </template>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="cancel">取 消</el-button>
      <el-button type="primary" @click="confirm">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
//api
import RoleManagement from '@/api/module/role-management'
import { addRoles, getUserRole } from '@/api/user'
export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false
    },
    formData: {
      type: Object,
      required: false
    }
  },
  data () {
    return {
      checkAll: false,
      checkedRole: [],
      optionList: [],
      roleIdList: [],
      isIndeterminate: true,
      dialogFormVisible: false,
      form: {
        nickName: '',
        userName: '',
        phoneNumber: '',
        email: '',
        userType: "platform_user"
      },
    };
  },
  watch: {
    showDialog: {
      handler (v) {
        this.dialogFormVisible = v
        v && (this.form = { ...this.form, ...this.formData })
        v && this.queryRoleManagement()
        v && this.queryUserRole()
      }
    }
  },
  methods: {
    handleCheckAllChange (val) {
      console.log(this.optionList)
      this.checkedRole = val ? this.roleIdList : [];
      this.isIndeterminate = false;
    },
    handlecheckedRoleChange (value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.roleIdList.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleIdList.length;
    },
    queryUserRole () {
      if (this.form.userId) {
        this.checkedRole = []
        getUserRole(this.form.userId).then(res => {
          // console.log(res, '5666')
          if (res && res.data) {
            res.data.forEach(role => {
              this.checkedRole.push(role.roleId)
            })
          } else {
            this.checkedRole = []
          }
        })
      }
    },
    queryRoleManagement () {
      RoleManagement.queryByCondition({}).then(res => {
        console.log(res)
        this.roleIdList = []
        if (res && res.data) {
          this.optionList = res.data
          res.data.forEach(item => {
            this.roleIdList.push(item.roleId)
          })
        } else {
          this.optionList = []
        }
      })
    },
    //关闭 isRef是否刷新表单
    close (isRef) {
      this.$emit('closeDialog', isRef)
      this.$refs.form.resetFields()
    },
    //取消
    cancel () {
      this.form = {
        nickName: '',
        userName: '',
        phoneNumber: '',
        email: '',
        userType: "platform_user"
      }
      this.close()
    },
    //确认
    confirm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          //  this.api 添加编辑接口 （注意传参）
          addRoles({
            roleIds: this.checkedRole,
            userId: this.form.userId
          }).then(res => {
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '操作成功!'
              });
              this.close(true)
            } else {
              this.$message({
                type: 'info',
                message: res.msg || '操作失败!'
              });
            }
          })
        } else {
          return false;
        }
      });
    }
  }
};
</script>